package com.xdl.flytest.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @Auther: 80736
 * @Date: 2018/12/25 11:51
 * @Description: 用户登录拦截器
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private List<String> excludedUrls;

    public List<String> getExcludedUrls() {
        return excludedUrls;
    }

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String url = request.getRequestURI();
        logger.debug("拦截成功，用户访问禁止：" + url);

        for (String excludedUrl : excludedUrls) {
            if (url.contains(excludedUrl)) {
                return true;
            }
        }

        if (session.getAttribute("email") != null) {
            return true;
        }

        response.sendRedirect("user/login");
        //request.getRequestDispatcher("/WEB-INF/views/user/page-login.html").forward(request, response);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //logger.debug("请求url: " + request.getRequestURL());
        if (ex != null) {
            logger.error(ex.getMessage());
        }
    }
}
